// SmarTest Studio - HTTP 客户端统一封装
// 提供与 axios 兼容的最小 API：get/delete/post/put/patch

function createAxiosLikeFetchClient() {
  const request = (url, options = {}) => {
    return fetch(url, options).then(async (resp) => {
      const contentType = resp.headers.get('content-type') || '';
      let data;
      if (contentType.includes('application/json')) {
        try { data = await resp.json(); } catch (_) { data = null; }
      } else {
        try { data = await resp.text(); } catch (_) { data = null; }
      }
      const response = {
        data,
        status: resp.status,
        statusText: resp.statusText,
        headers: Object.fromEntries(resp.headers.entries()),
        config: {},
        request: {}
      };
      if (!resp.ok) {
        const error = new Error('Request failed with status ' + resp.status);
        error.response = response;
        throw error;
      }
      return response;
    });
  };

  const buildBodyAndHeaders = (data, headers = {}) => {
    const outHeaders = { 'Content-Type': 'application/json', ...headers };
    if (data instanceof FormData) {
      delete outHeaders['Content-Type'];
      return { body: data, headers: outHeaders };
    }
    if (typeof data === 'string') {
      return { body: data, headers: outHeaders };
    }
    return { body: data != null ? JSON.stringify(data) : undefined, headers: outHeaders };
  };

  return {
    get: (url, config = {}) => request(url, { method: 'GET', headers: config.headers }),
    delete: (url, config = {}) => request(url, { method: 'DELETE', headers: config.headers }),
    post: (url, data, config = {}) => {
      const { body, headers } = buildBodyAndHeaders(data, config.headers);
      return request(url, { method: 'POST', headers, body });
    },
    put: (url, data, config = {}) => {
      const { body, headers } = buildBodyAndHeaders(data, config.headers);
      return request(url, { method: 'PUT', headers, body });
    },
    patch: (url, data, config = {}) => {
      const { body, headers } = buildBodyAndHeaders(data, config.headers);
      return request(url, { method: 'PATCH', headers, body });
    },
    defaults: {}
  };
}

export function getHttpClient() {
  if (typeof window !== 'undefined' && window.axios) {
    return window.axios;
  }
  return createAxiosLikeFetchClient();
}

const http = getHttpClient();
export default http;

// 提供给非模块脚本使用
if (typeof window !== 'undefined') {
  window.http = http;
}


